package com.softeem.musicserver.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softeem.musicserver.dto.R;
import com.softeem.musicserver.entity.Admin;
import com.softeem.musicserver.mapper.AdminMapper;
import com.softeem.musicserver.service.AdminService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 业务层实现类
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    public R login(Admin admin) {
        //select * from admin where username=?
        //获取查询条件构造器
        QueryWrapper<Admin> query = Wrappers.query(Admin.class);
        query.eq("username",admin.getUsername());
        //执行查询
        Admin one = getOne(query);
        if(Objects.isNull(one)){
            return R.fail().setMsg("账号不存在");
        }
        if(one.getStatus() != 0){
            return R.fail().setMsg("账号禁用").setCode(1);
        }

        //获取数据库中存储的随机盐组合输入密码加密
        String pwd = SecureUtil.md5(admin.getPassword() + one.getSalt());
        admin.setPassword(pwd);

        if(Objects.equals(one.getPassword(),admin.getPassword())){
            return R.ok().setMsg("登录成功").setData(one);
        }
        return R.fail().setMsg("密码错误").setCode(2);
    }

    @Override
    public R add(Admin admin) {
        //获取查询条件构造器
        QueryWrapper<Admin> query = Wrappers.query(Admin.class);
        query.eq("username",admin.getUsername());
        //执行查询
        Admin one = getOne(query);
        if(Objects.nonNull(one)){
            return R.fail().setMsg("该账号已存在");
        }
        //生成一个随机盐
        String salt = RandomUtil.randomString(6);
        //将随机盐和用户输入的密码组合加密
        String pwd = SecureUtil.md5(admin.getPassword() + salt);
        //将盐和加密后的密码添加到对象中
        admin.setSalt(salt);
        admin.setPassword(pwd);
        if(save(admin)){
            return R.ok().setMsg("添加成功").setData(admin);
        }
        return R.fail().setMsg("添加失败");
    }
}
